<template>
  <div class='main-menu'>
    <div class='logo'>
      <img class='img' src='@/assets/img/logo.svg' alt='' />
      <h2 v-show='!isFold' class='title'>后台管理系统</h2>
    </div>
    <div class='menu'>
      <el-menu :collapse='isFold' :default-active='defaultActive'>
        <template v-for='item in userMenus' :key='item.id'>
          <el-sub-menu :index='item.id.toString()'>
            <template #title>
              <el-icon>
                <component :is="item.icon.split('el-icon')[1]"></component>
              </el-icon>
              <span>
                {{ item.name }}
              </span>
            </template>

            <templage v-for='subItem in item.children' :key='subItem.id'>
              <el-menu-item
                :index='subItem.id.toString()'
                @click='handleItemClick(subItem)'
              >
                <span>
                  {{ subItem.name }}
                </span>
              </el-menu-item>
            </templage>
          </el-sub-menu>
        </template>
      </el-menu>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { useLoginStore } from '@/stores/login'
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { mapPathToMenu } from '@/utils/map-menus'

const props = defineProps({
  isFold: {
    type: Boolean,
    default: false
  }
})

const loginStore = useLoginStore()
const userMenus = loginStore.userMenus

const isCollapse = ref(false)

const router = useRouter()

const handleItemClick = (item: any) => {
  router.push(item.url)
}

const route = useRoute()

const defaultActive = ref(mapPathToMenu(route.path, userMenus).id + '')

watch(route, (newVal, oldVal) => {
  defaultActive.value = mapPathToMenu(newVal.path, userMenus).id + ''
})

</script>

<style scoped lang='less'>
.main-menu {
  height: 100%;
  background-color: #001529;

  .logo {
    display: flex;
    height: 28px;
    padding: 12px 10px 8px 10px;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    overflow: hidden;

    .img {
      height: 100%;
      margin: 0 10px;
    }

    .title {
      font-size: 16px;
      font-weight: 700;
      color: white;
      white-space: nowrap;
    }
  }
}

.el-menu {
  border-right: none;
  user-select: none;
  --el-menu-text-color: #fff;
  --el-menu-bg-color: #001529;
  --el-menu-hover-bg-color: none;

  .el-sub-menu {
    --el-menu-bg-color: #0c2135;

    .el-menu-item {
      --el-menu-active-color: #fff;
    }

    .el-menu-item.is-active {
      background-color: #0a60bd;
    }
  }
}
</style>
